package com.duanzz.sqlSession;

import com.duanzz.config.SQLType;
import com.duanzz.pojo.Configuration;
import com.duanzz.pojo.MappedStatement;

import java.lang.reflect.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Executor executor;

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration,Executor executor) {
        this.configuration = configuration;
        this.executor = executor;
    }

    @Override
    public <T> List<T> selectList(String statementId, Object... params) throws Exception {
        //将要完成查询对SimpleExecutor里的query方法的调用
        Executor executor = new SimpleExecutor();
        List<T> list = executor.doQuery(configuration, configuration.getMappedStatementMap().get(statementId), params);
        return list;

    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空或者返回结果过多!");
        }
    }

    @Override
    public int update(String statementId, Object... params) throws Exception {
        //修改操作交给 SimpleExecutor里的doUpdate方法的调用
        Executor executor = new SimpleExecutor();
        return executor.doUpdate(configuration, configuration.getMappedStatementMap().get(statementId), params);
    }

    @Override
    public int insert(String statementId, Object... params) throws Exception {
        //修改操作交给 SimpleExecutor里的doUpdate方法的调用
        Executor executor = new SimpleExecutor();
        return executor.doUpdate(configuration, configuration.getMappedStatementMap().get(statementId), params);

    }

    @Override
    public int delete(String statementId, Object... params) throws Exception {
        //修改操作交给 SimpleExecutor里的doUpdate方法的调用
        Executor executor = new SimpleExecutor();
        return executor.doUpdate(configuration, configuration.getMappedStatementMap().get(statementId), params);
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用jdk的动态代理，为Dao接口生成代理对象
        return (T) Proxy.newProxyInstance(mapperClass.getClassLoader(), new Class[]{mapperClass}, (proxy, method, args) -> {
            //invoke方法

            //底层还是去执行JDBC代码
            //根据不同情况 来调用selectList或者selectOne
            //  准备参数 : 1.statementId  接口全限定名+方法名
            String methodName = method.getName();
            String className = method.getDeclaringClass().getName();
            String statementId = className + "." + methodName;

            //在MappedStatement中加入了标记增删改查的标记 因此可以判断走哪个方法
            MappedStatement ms = configuration.getMappedStatementMap().get(statementId);
            if (ms.getSqlType().equals(SQLType.SELECT)) {
                //查询
                //准备参数：2.参数 params:args
                Type genericReturnType = method.getGenericReturnType();
                //判断是否进行了泛型类型参数化(如果是List泛型 则是查询结果集合 )
                if (genericReturnType instanceof ParameterizedType) {
                    List<Object> objects = selectList(statementId, args);
                    return objects;
                }
                return selectOne(statementId, args);

            } else{
                //新增 修改 删除
                return update(statementId,args);
            }

        });

    }

    @Override
    public void close() throws SQLException {
         executor.getThreadLocal().get().commit();
         executor.getThreadLocal().remove();
    }
}
